<template>
  <div>
    <!-- 本页面是个人页面的详细布局 -->
    <div class="book">
      <!-- 搜索框 -->
      <div style="text-align: right">
        <div class="select" style="margin: 10px auto 10px auto">
          <el-input
            size="small"
            class="searchInput"
            placeholder="请输入员工工号"
            style="width: 300px; margin-right: 15px"
            suffix-icon="el-icon-search"
            @keydown.enter.native="searchSubject"
            v-model="employeeId"
          >
          </el-input>
          <el-button
            size="small"
            style="margin-right: 60px"
            type="primary"
            @click="searchSubject"
            >搜索</el-button
          >
        </div>
      </div>
      <!-- 员工主体界面 -->
      <div>
        <el-row :gutter="24" style="height: 100%">
          <!--  员工基本信息、访问域名列表-->
          <el-col :span="8">
            <div class="grid-content bg-purple" style="height: 500px">
              <div id="card" style="height: 100px; margin-left: 80px">
                <div style="height: 20px"></div>
                <div>
                  员工编号：<span>{{ this.employeeInfo.empId }}</span>
                </div>
                <div>
                  所处部门：<span>{{ this.employeeInfo.depart }}</span>
                </div>
                <div>
                  职位：<span>{{ this.employeeInfo.identity}}</span>
                </div>
                <!-- <div>
                  工位IP：<span>{{ 444 }}</span>
                </div> -->
              </div>
              <!-- 访问域名列表 -->

              <div style="height: 400px; margin-left: 10px; margin-right: 10px">
                <el-table
                  :data="hostList1"
                  height="390"
                  border
                  style="width: 100%"
                >
                  <el-table-column prop="host" label="域名" width="180">
                  </el-table-column>
                  <el-table-column prop="time" sortable label="频数">
                  </el-table-column>
                </el-table>
              </div>
            </div>
          </el-col>
          <!-- 收发邮件词云图 -->
          <el-col :span="8">
            <div class="grid-content bg-purple" style="height: 500px">
              <div id="fromChart" style="height: 250px; weight: 100%"></div>
              <div id="toChart" style="height: 250px; weight: 100%"></div>
            </div>
          </el-col>
          <!-- 每日打卡时长、登录服务器图 -->
          <el-col :span="8">
            <div class="grid-content bg-purple" style="height: 500px">
              <div id="loginChart" style="height: 230px; weight: 100%"></div>
              <div id="warningInfo" style="height: 70px; weight: 100%"></div>
              <div id="checkChart" style="height: 200px; weight: 100%"></div>
            </div>
          </el-col>
        </el-row>
      </div>
    </div>
  </div>
</template>
<script>
    import * as d3 from 'd3';
    import 'echarts-wordcloud';

export default {
  data() {
    return {
      hostList1: [],
      employeeId: this.$route.params.id,
      total: [],
      // name: "",
      employeeInfo: '',
      wordCloudFromData: [],
      wordCloudToData: [],
    };
  },
  mounted() {
    this.searchSubject();
    
  },
  methods: {
    // 渲染两个词云以及登录和打卡时长图
    render(){
      this.renderWordCloud(),
      this.renderLineChart()
    },
    async renderWordCloud(){
      this.wordCloudFromData = await this.getWordsCloudFromData();
      // console.log("this.wordCloudFromData", this.wordCloudFromData);
      this.drawWordCloudFrom()
      this.wordCloudToData = await this.getWordsCloudToData();
      this.drawWordCloudTo()
    },
    async getWordsCloudFromData(){
      var data =  await d3.csv("/static/data/wordcloud_from.csv");
      return data
    },
    async getWordsCloudToData(){
      var data =  await d3.csv("/static/data/wordcloud_to.csv");
      return data
    },
    drawWordCloudFrom() {
      
            var input = this.employeeId;
            // console.log("input", input);
            // 过滤数据，只保留与输入字符匹配的行
            var filteredData = this.wordCloudFromData.filter(function(d) {
                return d.from.startsWith(input);
            });

            // 提取词云数据
            var wordCloudData = filteredData.map(function(d) {
                return {
                    name: d.word,
                    value: +d.count
                };
            });

            // 使用ECharts绘制词云图
            var chart = this.$echarts.init(document.getElementById('fromChart'));
            var option = {
              title: {
          text: '发送主题词',
          // backgroundColor:'rgb(128, 128, 128)',
          //subtext: '人力部门',
          x: 'center',
          padding:[5,2]
        },
                series: [{
                    type: 'wordCloud',
                    shape: 'circle',
                    left: 'center',
                    top: 'center',
                    width: '80%',
                    height: '80%',
                    data: wordCloudData,
                    textStyle: {
                        normal: {
                            fontFamily: 'sans-serif'
                        }
                    }
                }]
            };
            chart.setOption(option);
        },
        drawWordCloudTo() {
      
      var input = this.employeeId;
      // console.log("input", input);
      // 过滤数据，只保留与输入字符匹配的行
      var filteredData = this.wordCloudToData.filter(function(d) {
          return d.to.startsWith(input);
      });

      // 提取词云数据
      var wordCloudData = filteredData.map(function(d) {
          return {
              name: d.word,
              value: +d.count
          };
      });

      // 使用ECharts绘制词云图
      var chart = this.$echarts.init(document.getElementById('toChart'));
      var option = {
        title: {
    text: '接收主题词',
    // backgroundColor:'rgb(128, 128, 128)',
    //subtext: '人力部门',
    x: 'center',
    padding:[5,2]
  },
          series: [{
              type: 'wordCloud',
              shape: 'circle',
              left: 'center',
              top: 'center',
              width: '80%',
              height: '80%',
              data: wordCloudData,
              textStyle: {
                  normal: {
                      fontFamily: 'sans-serif'
                  }
              }
          }]
      };
      chart.setOption(option);
  },
  renderLineChart(){
    // 打卡时长统计
      this.generateChart();
      // 登陆错误次数统计
      this.fetchData()
    },
    fetchData() {
        var userId = this.employeeId;
        var threshold = 2;

        fetch('/static/data/login.json')
            .then(response => response.json())
            .then(data => {
                var userErrorData = data[userId];
                var xAxisData = [];
                var seriesData = [];

                for (var date in userErrorData) {
                    if (userErrorData.hasOwnProperty(date)) {
                        var errorCount = userErrorData[date].error_count;
                        var lastErrorTime = userErrorData[date].last_error_time;
                        var symbolSize = 10 + (errorCount * 2); // 基础大小为10，可以根据需要调整
                        
                        var itemStyle = { color: errorCount >= threshold ? 'red' : 'green' };
                        console.log(errorCount,1,threshold,2,itemStyle)
                        xAxisData.push(date);
                        seriesData.push({
                            name: date,
                            value: [date, errorCount, lastErrorTime],
                            itemStyle: itemStyle,
                            symbolSize: symbolSize
                        });

                        // 输出警告信息
                        if (errorCount >= threshold) {
                            var warningDiv = document.getElementById('warningInfo');
                            warningDiv.innerHTML = '警告！用户 ' + userId + ' 在 ' + date + ' 存在异常登陆情况，最后一次错误时间为 ' + lastErrorTime;
                        }
                    }
                }

                var chartDom = document.getElementById('loginChart');
                var myChart = this.$echarts.init(chartDom);
                var option;

                option = {
                  grid: {
              //  top:'10%',
               left: '3%',
               right: '3%',
               bottom: '2%',
               containLabel: true
           },
                  title: {
                    text: '用户登录错误次数统计'
                },
                    xAxis: {
                        type: 'category',
                        data: xAxisData
                    },
                    yAxis: {
                        type: 'value'
                    },
                    series: [{
                        data: seriesData,
                        type: 'scatter'
                    }]
                };

                myChart.setOption(option);
            })
            .catch(error => {
                console.error('数据获取失败:', error);
            });
    },
    async  generateChart() {
        // 获取用户输入的 ID
        const inputId = this.employeeId;
        try {
            // 使用 fetch 加载文本文件
            const response = await fetch('/static/data/output.txt');
            const dataText = await response.text();
          // console.log(dataText)
            // 解析文本数据为 JSON 对象
            const jsonData = JSON.parse(dataText);
            // console.log("jsonData",jsonData)
            // console.log("inputId", inputId)
            // 根据输入的 ID 筛选相应的数据
            const filteredData = jsonData.filter(item => item.id == inputId);
            // console.log("filteredData",filteredData)
            // ...（以下代码与之前提供的代码相同）
            // 提取日期和打卡次数的数组
            const days = filteredData.map(item => item.day);
            const dakas = filteredData.map(item => item.daka);
            // console.log("dakas",dakas)
            // 初始化 ECharts 图表
            const myChart = this.$echarts.init(document.getElementById('checkChart'));

            // 图表的配置选项
            const option = {
              grid: {
               top:'15%',
               left: '3%',
               right: '3%',
               bottom: '5%',
               containLabel: true
           },
                title: {
                    text: '用户打卡时长图'
                },
                xAxis: {
                    type: 'category',
                    data: days,
                    // X轴标签的间隔和旋转角度
                    axisLabel: {
                        interval: 0,
                        rotate: 45
                    }
                },
                yAxis: {
                    type: 'value'
                },
                series: [{
                    data: dakas,
                    type: 'bar',
                    itemStyle: {
                        // 设置柱状图颜色，大于8的部分标红
                        color: function(params) {
                          // console.log(params.value,121)
                            return params.value > 9 ? 'red' : 'green';
                        }
                    }
                }]
            };

            // 设置图表的配置选项
            myChart.setOption(option);

            // 如果筛选后的数据条目超过15条，启用数据缩放功能
            if (filteredData.length > 15) {
                myChart.setOption({
                    dataZoom: [
                        {
                            type: 'slider',
                            start: 0,
                            end: 50
                        }
                    ]
                });
            }
        }
         catch (error) {
            console.error('Error reading or parsing data:', error);
        }
    },
    getHost() {
      this.$router.push('/vis/person/' + this.employeeId)
      this.$http({
        method: "get",
        url: "weblog/weblogById",
        params: {
          empId: this.employeeId,
        },
      }).then((res) => {
        res = res.data;
        // console.log(res);
        var json1 = {};
        for (var i = 0; i < res.length; i++) {
          var key = res[i].host;
          if (key != null) {
            if (json1[key]) {
              //去重+统计
              //存在
              json1[key]++; //取出属性值+1
            } else {
              //不存在
              json1[key] = 1; //做一个属性赋值1
            }
          }
        }
        // console.log("111",json1)
        let hostList = [];
        // for(var i=0;i<json1.length;i++){
        for (const [key, value] of Object.entries(json1)) {
          let hosttem = {};
          hosttem.host = key;
          hosttem.time = value;
          hostList.push(hosttem);
          // console.log("222",key,hosttem)
        }
        this.hostList1 = hostList;
      });
    },
    getIdentity(){
      this.$http({
          method: 'get',
          url: 'employee/findByEmpId',
          params: {
            'empid': this.employeeId
          }
        }).then(res => {
          // console.log(res)
          res = res.data
          this.employeeInfo = res
        })
    },
    // 页面初始化
    searchSubject() {
      this.getHost()
      this.getIdentity()
      var warningDiv = document.getElementById('warningInfo');
                            warningDiv.innerHTML = '';
      this.render();
    },
  },
};
</script>
<style>
.total {
  margin-top: 10px;
}
</style>
